<template>
  <div class="v-permission-table">
    <table border="1px" width="100%">
      <thead>
      <th width="30%">角色</th>
      <th width="70%">子权限</th>
      </thead>
      <tbody>
      <tr v-for="role in rolesData">
        <td>
          <el-checkbox :indeterminate="role.isIndeterminate" v-model="role.checkAll"
                       @change="rootNodeCheck($event,role)">{{role.name}}
          </el-checkbox>
        </td>
        <td>
          <el-checkbox-group v-model="role.selectArray" @change="childNodeCheck($event,role)">
            <el-checkbox v-for="perm in role.pids" :label="perm.flag" :value="perm.flag" :key="perm._id">{{perm.name}}
            </el-checkbox>
          </el-checkbox-group>
        </td>
      </tr>
      </tbody>
    </table>

  </div>
</template>

<script>
  export default {
    name: "index",
    data: function () {
      return {
        checkAll: undefined
      }
    },

    props: {
      roles: {
        type: Array,
        default: function () {
          return []
        }
      },
      value: {
        type: Array,
        default: function () {
          return [];
        }
      }
    },
    model: {
      prop: 'value',
      event: 'change'
    },
    methods: {
      //根节点选中
      rootNodeCheck($event, role) {
        role.isIndeterminate = false;
        role.selectArray = [];
        if ($event) {
          role.selectArray = role.pids.map((o, i, a) => o.flag);
        }
        let selectAll = [];
        for (let i = 0; i < this.rolesData.length; i++) {
          selectAll = selectAll.concat(this.rolesData[i].selectArray);
        }
        this.$emit('change', selectAll); //返回所有的selectArray
      },
      //字节点选中
      childNodeCheck($event, role) {
        //判断子权限
        role.checkAll = $event.length === role.pids.length;
        role.isIndeterminate = $event.length < role.pids.length && $event.length > 0;
        let selectAll = [];
        for (let i = 0; i < this.rolesData.length; i++) {
          selectAll = selectAll.concat(this.rolesData[i].selectArray);
        }
        this.$emit('change', selectAll); //返回所有的selectArray
      }
    },
    computed: {
      rolesData: function () {
        return this.roles.map((o, i, a) => {
          const ids = o.pids.filter(p=>{
            return this.value.indexOf(p.flag)!=-1
          }).map(o=>o.flag);
          this.$set(o, 'selectArray', ids);
          this.$set(o, 'isIndeterminate', ids.length > 0 && ids.length < o.pids.length);
          this.$set(o, 'checkAll', ids.length === o.pids.length);
          return o;
        })
      }
    }
  }
</script>

<style scoped>
  .v-permission-table {
    max-height: 500px;
  }

  .v-permission-table table {

  }

  .v-permission-table table thead th {
    padding: 10px;
  }

  .v-permission-table table tbody {
    max-height: 500px;
    overflow-y: scroll;
  }
</style>
